

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Vector;


public class TwitterServer {
	Connection myConnection;
	ClientHandler clientHandler;
	ServerSocket server;
	int port = 8080;
	int i = 0;
	static Vector<ClientHandler> cHandlersList = new Vector<ClientHandler>();
	
	public TwitterServer() {
		try {
			myConnection = getConnection();
			server = new ServerSocket(port);
			Updater updater = new Updater(myConnection, "updater");
			updater.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * handle the requests of the clients
	 * makes a new Thread if list is empty
	 */
	public void handleConnection() {
		while (true) {
			try {
				Socket socket = server.accept();
				synchronized (cHandlersList) {
					if(cHandlersList.isEmpty()){
						ClientHandler cHandler = new ClientHandler(myConnection, socket, String.valueOf(i));
						cHandler.start();
						i++;
					}else{
						ClientHandler cHandler = cHandlersList.firstElement();
						cHandler.setSocket(socket);
						cHandlersList.remove(cHandler);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * build a connection with the DB
	 * @return Connection
	 */
	public static Connection getConnection() {
		Connection con = null;
		Statement statement = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost/twitterdb", "root", "dbpro");
			// set the updating of the user table to 0.
			statement = con.createStatement();
			statement.executeUpdate("UPDATE user SET updating = 0");
		} catch (Exception e) {
			System.err.println("Exception : " + e.getMessage());
		}
		return con;
	}

	public static void main(String[] args) {
		TwitterServer tServer = new TwitterServer();
		tServer.handleConnection();
	}
}
